package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Tag;
import com.itheima.ydd.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/ydd_tag")
public class TagController {
    @Autowired
    private TagService tagService;

    /**
     * 查询方法
     *
     * @param tagname
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(String tagname, Integer page, Integer limit) {
        log.info("查询数据为:{}", tagname, page, limit);
        //构造分页器
        IPage<Tag> pageInfo = new Page<>(page, limit);
        //条件构造器
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.like(StringUtils.isNotEmpty(tagname), Tag::getTagname, tagname);
        //添加排序条件
        queryWrapper.orderByDesc(Tag::getId);

        tagService.page(pageInfo, queryWrapper);

        List<Tag> tags = pageInfo.getRecords();

        PageResult init = PageResult.init(pageInfo.getTotal(), pageInfo.getSize(), pageInfo.getPages(), tags);
        return ResultData.ok("", init);
    }

    /**
     * 修改
     *
     * @param tag
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody Tag tag) {
        log.info("修改数据为:{}", tag);
        tagService.updateById(tag);
        return ResultData.ok("", "成功");
    }

    /**
     * 标签详情
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(@RequestParam Integer id) {
        log.info("id为;{}", id);
        // Tag byId = tagService.getById(id);

        return ResultData.ok("", tagService.getById(id));
    }

    /**
     * 新增方法
     *
     * @param tag
     * @return
     */
    @PostMapping("/add")
    public ResultData save(@RequestBody Tag tag) {
        log.info("新增数据为:{}", tag);
        tag.setDefault_data("1");
        tagService.save(tag);
        return ResultData.ok("", "成功");
    }

    @GetMapping("/del")
    public ResultData del(@RequestParam Integer id) {
        log.info("id为:{}", id);
        tagService.removeById(id);
        return ResultData.ok("", "成功");
    }

    @GetMapping("/all")
    public ResultData all(){
return ResultData.ok("",tagService.list());
    }
}
